package com.zmj.sy.mom.srv.aps.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.DictData;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.DictType;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.Group;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.PhaseGroup;
import com.zmj.sy.mom.srv.aps.bean.entity.third.SinoCamPushPlan;
import com.zmj.sy.mom.srv.aps.bean.entity.third.SinoCamReceiveNestPart;
import com.zmj.sy.mom.srv.aps.bean.entity.workQueue.NoPlateWorkQueueTaskDetail;
import com.zmj.sy.mom.srv.aps.bean.entity.workQueue.PlateWorkQueueTaskDetail;
import com.zmj.sy.mom.srv.aps.bean.entity.workQueue.WorkqueueNetDetail;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseListResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BasePageResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.Result;
import com.zmj.sy.mom.srv.aps.bean.vo.dictdata.DictDataFindReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.workQueue.*;
import com.zmj.sy.mom.srv.aps.config.ProjectConfig;
import com.zmj.sy.mom.srv.aps.mapper.*;
import com.zmj.sy.mom.srv.aps.utils.PkgUtils;
import com.zmj.sy.mom.srv.aps.utils.mybatisplus.WrapperUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@RequiredArgsConstructor
@Service
public class WorkQueueService {
    private final PhaseGroupMapper phaseMapper;
    private final WorkQueueMapper baseMapper;
    private final ApsOrderService apsOrderService;
    private final DictDataMapper dictDataMapper;
    private final DictTypeMapper dictTypeMapper;
    private final GroupMapper groupMapper;
    private final OrderMapper orderMapper;
    private final WorkDetailTaskMapper workDetailTaskMapper;
    private final ApsWorkDetailMapper apsWorkDetailMapper;
    private final CompleteReportMapper completeReportMapper;
    private final SinoCamReceiveNestPartMapper sinoCamReceiveNestPartMapper;
    private final ProjectConfig projectConfig;
    private final SinoCamPushPlanMapper sinoCamPushPlanMapper;

    /**
     * @Description: 获取完工率
     * @author: hejiahui
     * @since: 2024/9/19 8:43
     */
    public BaseListResVo<WorkQueueGanttChartResVo> workQueueFinishRate(WorkQueueGanttChartReqVo reqVo) {
        if (reqVo.getWorkArea().equals("nest")) {
            if (reqVo.getPlanStartDateTime() == null) {
                String startDate = LocalDate.now().minusDays(7) + " 07:00:00";
                LocalDateTime startTime = LocalDateTime.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                reqVo.setPlanStartDateTime(startTime);
            } else {
                reqVo.setPlanStartDateTime(reqVo.getPlanStartDateTime().plusHours(7));
            }

            if (reqVo.getPlanEndDateTime() == null) {
                String endDate = LocalDate.now().plusDays(7) + " 07:00:00";
                LocalDateTime endTime = LocalDateTime.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                reqVo.setPlanEndDateTime(endTime);
            } else {
                reqVo.setPlanEndDateTime(reqVo.getPlanEndDateTime().plusHours(7));
            }

            WorkQueueGanttChartResVo qg1 = new WorkQueueGanttChartResVo();
            qg1.setStationId(45);
            qg1.setStationCode("1-2_JGQG_00");
            qg1.setStationName("1-2激光切割1组");


            WorkQueueGanttChartResVo qg2 = new WorkQueueGanttChartResVo();
            qg2.setStationId(46);
            qg2.setStationCode("1-3_JGQG_00");
            qg2.setStationName("1-3激光切割2组");
            qg2.setPlanCount(0);
            qg2.setFinishCount(0);
            qg2.setFinishRate(0.0);

            WorkQueueGanttChartResVo qg3 = new WorkQueueGanttChartResVo();
            qg3.setStationId(47);
            qg3.setStationCode("1-1_HYQG_00");
            qg3.setStationName("1-1火焰切割1组");
            qg3.setPlanCount(0);
            qg3.setFinishCount(0);
            qg3.setFinishRate(0.0);

            ArrayList<WorkQueueGanttChartResVo> resultList = new ArrayList<>();
            resultList.add(qg3);
            resultList.add(qg1);
            resultList.add(qg2);

            List<SinoCamPushPlan> list = sinoCamPushPlanMapper.countFinishByDate(reqVo.getPlanStartDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), reqVo.getPlanEndDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            Map<String, SinoCamPushPlan> collect = list.stream().collect(Collectors.toMap(e -> e.getMesOrderCode(), Function.identity(), (a, b) -> a));

            for (WorkQueueGanttChartResVo workQueueGanttChartResVo : resultList) {
                SinoCamPushPlan countR = collect.get(workQueueGanttChartResVo.getStationCode());
                if(countR == null){
                    continue;
                }
                workQueueGanttChartResVo.setPlanCount(countR.getPlanAmount().intValue());
                workQueueGanttChartResVo.setFinishCount(countR.getPlanFinishAmount().intValue());
                if (workQueueGanttChartResVo.getFinishCount() != 0) {
                    double rate = Math.round((float) workQueueGanttChartResVo.getFinishCount() / workQueueGanttChartResVo.getPlanCount() * 10000) / 100.0;
                    workQueueGanttChartResVo.setFinishRate(rate);
                }
            }

            return new BaseListResVo<>(resultList);
        }


        if (ObjectUtils.isNotEmpty(reqVo.getPhases())) {
            LambdaQueryWrapper<PhaseGroup> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(PhaseGroup::getPhaseCode, reqVo.getPhases());
            wrapper.eq(PhaseGroup::getDeleted, 0);
            List<PhaseGroup> phaseGroups = phaseMapper.selectList(wrapper);
            List<String> groups = phaseGroups.stream().map(PhaseGroup::getGroupCode).collect(Collectors.toList());
            List<Group> groupList = groupMapper.lambdaQuery().in(Group::getMyCode, groups).list();
            List<Integer> plateGroupIdList = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(groupList)) {
                plateGroupIdList = groupList.stream().map(Group::getId).collect(Collectors.toList());
            }
            if (ObjectUtils.isEmpty(reqVo.getGroupIds())) {
                reqVo.setGroupIds(plateGroupIdList);
            }

        } else {

            //获取工作组
            QueryWrapper<DictType> typeQuery = new QueryWrapper<>();
            typeQuery.eq("dict_code", reqVo.getWorkArea());
            List<DictType> dictTypes = dictTypeMapper.selectList(typeQuery);
            if (ObjectUtils.isEmpty(dictTypes)) {
                return BaseListResVo.empty();
            }
            if (reqVo.getPlanStartDateTime() == null) {
                String startDate = LocalDate.now().minusDays(7) + " 07:00:00";
                LocalDateTime startTime = LocalDateTime.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                reqVo.setPlanStartDateTime(startTime);
            } else {
                reqVo.setPlanStartDateTime(reqVo.getPlanStartDateTime().plusHours(7));
            }

            if (reqVo.getPlanEndDateTime() == null) {
                String endDate = LocalDate.now().plusDays(7) + " 07:00:00";
                LocalDateTime endTime = LocalDateTime.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                reqVo.setPlanEndDateTime(endTime);
            } else {
                reqVo.setPlanEndDateTime(reqVo.getPlanEndDateTime().plusHours(7));
            }

            QueryWrapper<DictData> dictWrapper = new QueryWrapper<>();
            dictWrapper.eq("dict_type", dictTypes.get(0).getId());
            List<DictData> dictData = dictDataMapper.selectList(dictWrapper);
            List<Integer> plateGroupIdList = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(dictData)) {
                plateGroupIdList = dictData.stream().map(e -> Integer.parseInt(e.getDictValue())).collect(Collectors.toList());
            }
            if (ObjectUtils.isEmpty(reqVo.getGroupIds())) {
                reqVo.setGroupIds(plateGroupIdList);
            }
        }
        if (reqVo.getWorkArea().equals("smartCuttingArea-plate")) {
            return this.getPlateFinishRate(reqVo);
        } else {
            return this.getNoPlateFinishRate(reqVo);
        }
    }

    /**
     * @Description: 钢板工位的完成率
     * @author: hejiahui
     * @since: 2024/9/19 14:09
     */
    private BaseListResVo<WorkQueueGanttChartResVo> getPlateFinishRate(WorkQueueGanttChartReqVo reqVo) {

        QueryWrapper<?> infoQuery = new QueryWrapper<>();
        infoQuery.in("gr.id", reqVo.getGroupIds());
        infoQuery.eq("det.type", 1);

        if (reqVo.getPlanStartDateTime() != null) {
            infoQuery.ge("det.plan_start_date_time", reqVo.getPlanStartDateTime());
        } else {
            infoQuery.ge("det.plan_start_date_time", LocalDateTime.now().minusDays(7));
        }
        if (reqVo.getPlanEndDateTime() != null) {
            reqVo.setPlanEndDateTime(reqVo.getPlanEndDateTime().plusDays(1));
            infoQuery.le("det.plan_start_date_time", reqVo.getPlanEndDateTime());
        } else {
            infoQuery.le("det.plan_start_date_time", LocalDateTime.now().plusDays(7));
        }

        if (reqVo.getStatus() != null) {
            if (reqVo.getStatus() < 4) {
                infoQuery.lt("det.status", 4);
            } else {
                infoQuery.eq("det.status", reqVo.getStatus());
            }

        }

        if (CollUtil.isNotEmpty(reqVo.getOrderNos())) {
            infoQuery.in("o.construct_no", reqVo.getOrderNos());
        }

        List<WorkQueueGanttChartResVo> detailList = baseMapper.getPlateWorkQueueRate(infoQuery);
        detailList.forEach(e -> {
            double rate = Math.round((float) e.getFinishCount() / e.getPlanCount() * 10000) / 100.0;
            e.setFinishRate(rate);
        });
        return BaseListResVo.of(detailList, WorkQueueGanttChartResVo.class);
    }

    private List<WorkQueueGanttChartResVo> convertCompare(List<WorkQueueGanttChartResVo> resVoList, WorkQueueGanttChartReqVo reqVo) {
        Map<String, String> compareType = reqVo.getCompareType();
        List<WorkQueueGanttChartResVo> resultList = new ArrayList<>();
        if (StrUtil.isNotEmpty(reqVo.getStationName())) {
            resultList = resVoList.stream().filter(e -> reqVo.getStationName().contains(e.getStationName())).collect(Collectors.toList());
        }
        if (reqVo.getPlanCount() != null) {
            String str = MapUtil.getStr(compareType, "planCount");
            resultList = resVoList.stream().filter(e -> WrapperUtil.fixWrapper(str, e.getPlanCount(), reqVo.getPlanCount())).collect(Collectors.toList());
        }

        if (reqVo.getFinishCount() != null) {
            String str = MapUtil.getStr(compareType, "finishCount");
            resultList = resVoList.stream().filter(e -> WrapperUtil.fixWrapper(str, e.getFinishCount(), reqVo.getFinishCount())).collect(Collectors.toList());
        }

        if (reqVo.getFinishRate() != null) {
            String str = MapUtil.getStr(compareType, "finishRate");
            resultList = resVoList.stream().filter(e -> WrapperUtil.fixWrapper(str, e.getFinishRate(), reqVo.getFinishRate())).collect(Collectors.toList());


        }
        if (CollectionUtils.isEmpty(resultList)) {
            resultList = resVoList;
        }
        return resultList;
    }

    /**
     * @Description: 非钢板工位的完成率
     * @author: hejiahui
     * @since: 2024/9/19 13:58
     */
    private BaseListResVo<WorkQueueGanttChartResVo> getNoPlateFinishRate(WorkQueueGanttChartReqVo reqVo) {

        QueryWrapper<?> infoQuery = new QueryWrapper<>();
        infoQuery.in("gr.id", reqVo.getGroupIds());
        infoQuery.eq("det.type", 2);
        infoQuery.ne("det.order_type", 2);
        infoQuery.in(ObjectUtils.isNotEmpty(reqVo.getOrderNos()), "ao.construct_no", reqVo.getOrderNos());

        if (reqVo.getPlanStartDateTime() != null) {
            infoQuery.ge("det.plan_start_date_time", reqVo.getPlanStartDateTime());
        } else {
            infoQuery.ge("det.plan_start_date_time", LocalDateTime.now().minusDays(7));
        }
        if (reqVo.getPlanEndDateTime() != null) {
            reqVo.setPlanEndDateTime(reqVo.getPlanEndDateTime().plusDays(1));
            infoQuery.le("det.plan_start_date_time", reqVo.getPlanEndDateTime());
        } else {
            infoQuery.le("det.plan_start_date_time", LocalDateTime.now().plusDays(7));
        }
        if (reqVo.getStatus() != null) {
            if (reqVo.getStatus() < 4) {
                infoQuery.lt("det.status", 4);
            } else {
                infoQuery.eq("det.status", reqVo.getStatus());
            }
        }
        List<WorkQueueGanttChartResVo> detailList = baseMapper.getPlateWorkQueueRate(infoQuery);
        detailList.forEach(e -> {
            double rate = Math.round((float) e.getFinishCount() / e.getPlanCount() * 10000) / 100.0;
            e.setFinishRate(rate);
        });
        return BaseListResVo.of(detailList, WorkQueueGanttChartResVo.class);


    }

    /**
     * @Description: 获取队列明细
     * @author: hejiahui
     * @since: 2024/9/19 16:46
     */
    public BasePageResVo<WorkQueueTaskDetailResVo> getWorkQueueDetail(WorkQueueTaskDetailReqVo reqVo) {

        if (reqVo.getWorkArea().equals("nest")) {
            if(reqVo.getPlanStartDateTime() == null){
                reqVo.setPlanStartDateTime(LocalDateTime.now());
            }

            if(reqVo.getPlanEndDateTime() == null){
                reqVo.setPlanEndDateTime(reqVo.getPlanStartDateTime().plusDays(7));
            }

//            WHERE (plan.need_date >= #{startDateTime} AND plan.need_date <= #{endDateTime} AND plan.version_brief = 'V2') " +
//            " GROUP BY awd.group_code ORDER BY awd.group_code ASC
            QueryWrapper<SinoCamPushPlan> query = Wrappers.query();
            query.ge("need_date", reqVo.getPlanStartDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            query.le("need_date", reqVo.getPlanEndDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            query.eq("version_brief", "V2");

            Page<WorkQueueTaskDetailResVo> l = sinoCamPushPlanMapper.findByDate(reqVo.toPage(), query);
            for (WorkQueueTaskDetailResVo record : l.getRecords()) {
                record.setStatus(1);
                record.setPackageNo(PkgUtils.gen(Integer.parseInt(record.getPackageNo())));
                record.setPlanCount(record.getOrderCnt() - record.getFinishCount());
            }
            return BasePageResVo.of(l, WorkQueueTaskDetailResVo.class);
        }

        if (ObjectUtils.isNotEmpty(reqVo.getPhases())) {
            LambdaQueryWrapper<PhaseGroup> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(PhaseGroup::getPhaseCode, reqVo.getPhases());
            wrapper.eq(PhaseGroup::getDeleted, 0);
            List<PhaseGroup> phaseGroups = phaseMapper.selectList(wrapper);
            List<String> groups = phaseGroups.stream().map(PhaseGroup::getGroupCode).collect(Collectors.toList());
            List<Group> groupList = groupMapper.lambdaQuery().in(Group::getMyCode, groups).list();
            List<Integer> plateGroupIdList = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(groupList)) {
                plateGroupIdList = groupList.stream().map(Group::getId).collect(Collectors.toList());
            }
            if (ObjectUtils.isEmpty(reqVo.getGroupIds())) {
                reqVo.setGroupIds(plateGroupIdList);
            }

        } else {
            //获取工作组
            QueryWrapper<DictType> typeQuery = new QueryWrapper<>();
            typeQuery.eq("dict_code", reqVo.getWorkArea());
            List<DictType> dictTypes = dictTypeMapper.selectList(typeQuery);
            if (ObjectUtils.isEmpty(dictTypes)) {
                return BasePageResVo.empty();
            }
            if (reqVo.getPlanStartDateTime() == null) {
                reqVo.setPlanStartDateTime(LocalDateTime.now().minusDays(7));
            }

            if (reqVo.getPlanEndDateTime() == null) {
                reqVo.setPlanEndDateTime(LocalDateTime.now().plusDays(7));
            }
            QueryWrapper<DictData> dictWrapper = new QueryWrapper<>();
            dictWrapper.eq("dict_type", dictTypes.get(0).getId());
            List<DictData> dictData = dictDataMapper.selectList(dictWrapper);
            List<Integer> plateGroupIdList = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(dictData)) {
                plateGroupIdList = dictData.stream().map(e -> Integer.parseInt(e.getDictValue())).collect(Collectors.toList());
            }
            if (ObjectUtils.isEmpty(reqVo.getGroupIds())) {
                reqVo.setGroupIds(plateGroupIdList);
            }
        }


        if (reqVo.getWorkArea().equals("smartCuttingArea-plate")) {
            return getPlateWorkQueueDetail(reqVo);
        } else {
            return getNoPlateWorkQueueDetail(reqVo);
        }
    }

    /**
     * @Description: 获取钢板队列明细
     * @author: hejiahui
     * @since: 2024/9/19 16:48
     */
    private BasePageResVo<WorkQueueTaskDetailResVo> getPlateWorkQueueDetail(WorkQueueTaskDetailReqVo reqVo) {
        Map<String, String> compareType = reqVo.getQueryType();

        //获取工作组信息
        List<Group> groups = groupMapper.selectList(new QueryWrapper<Group>().in("id", reqVo.getGroupIds())).stream().collect(Collectors.toList());
        if (ObjectUtils.isEmpty(groups)) {
            return BasePageResVo.empty();
        }
        //获取加工列表信息
        QueryWrapper<?> infoQuery = new QueryWrapper<>();
        //添加筛选条件
        infoQuery.eq("det.type", 1);
        if (reqVo.getPlanStartDateTime() != null) {
            infoQuery.ge("det.plan_start_date_time", reqVo.getPlanStartDateTime());
        } else {
            infoQuery.ge("det.plan_start_date_time", LocalDateTime.now().minusDays(7).toString());
        }
        if (reqVo.getPlanEndDateTime() != null) {
            infoQuery.le("det.plan_start_date_time", reqVo.getPlanEndDateTime().plusDays(1));
        } else {
            infoQuery.le("det.plan_start_date_time", LocalDateTime.now().plusDays(7).toString());
        }
        if (reqVo.getStatus() != null) {
            if (reqVo.getStatus() < 4) {
                infoQuery.lt("det.status", 4);
            } else {
                infoQuery.eq("det.status", reqVo.getStatus());
            }
        }

        if(CollUtil.isNotEmpty(reqVo.getOrderNos())){
            infoQuery.in("ord.construct_no", reqVo.getOrderNos());
        }

        infoQuery.in("det.group_code", groups.stream().map(Group::getMyCode).collect(Collectors.toList()));
        infoQuery.like(StringUtils.isNotBlank(reqVo.getNestingCode()), "pla.nest_id", reqVo.getNestingCode());
        infoQuery.like(StringUtils.isNotBlank(reqVo.getPlateNo()), "pick.material_id", reqVo.getPlateNo());
        infoQuery.like(StringUtils.isNotBlank(reqVo.getSizeMaterial()), "pick.plate_material", reqVo.getSizeMaterial());
        infoQuery.like(StringUtils.isNotBlank(reqVo.getRequisition()), "pick.picking_list_no", reqVo.getRequisition());
        if (ObjectUtils.isNotEmpty(reqVo.getThick())) {
            WrapperUtil.fixWrapper(infoQuery, "pla.norm", compareType.get("thick"), reqVo.getThick());
        }
        if (ObjectUtils.isNotEmpty(reqVo.getPlateLength())) {
            WrapperUtil.fixWrapper(infoQuery, "pla.length", compareType.get("plateLength"), reqVo.getPlateLength());
        }
        if (ObjectUtils.isNotEmpty(reqVo.getPlateWide())) {
            WrapperUtil.fixWrapper(infoQuery, "pla.width", compareType.get("plateWide"), reqVo.getPlateWide());
        }


        //添加排序条件
        String orderStr = "det.plan_start_date_time";
        if (StringUtils.isNotBlank(reqVo.getSort())) {
            if ("planStartTime".equals(reqVo.getSort())) {
                orderStr = "det.plan_start_date_time";
            } else if ("planEndTime".equals(reqVo.getSort())) {
                orderStr = "det.plan_end_date_time";
            } else if ("startTime".equals(reqVo.getSort())) {
                orderStr = "det.actual_start_date_time";
            } else if ("endTime".equals(reqVo.getSort())) {
                orderStr = "det.actual_end_date_time";
            }
        }
        if (StringUtils.isNotBlank(reqVo.getOrder())) {
            if ("desc".equals(reqVo.getOrder())) {
                infoQuery.orderByDesc(orderStr);
            } else {
                infoQuery.orderByAsc(orderStr);
            }
        } else {
            infoQuery.orderByAsc(orderStr);
        }
        Page<PlateWorkQueueTaskDetail> detailList = baseMapper.getPlateWorkQueueDetail(reqVo.toPage(), infoQuery);


        List<PlateWorkQueueTaskDetail> records = detailList.getRecords();
        if (CollUtil.isEmpty(records)) {
            return BasePageResVo.empty();
        }

        //生成状态  状态:1等待已领料、2就绪、3生产中、4生产已晚、5已晚、6完工、7完工已晚、8等待未领料
        for (PlateWorkQueueTaskDetail e : detailList.getRecords()) {
            e.setPlateLength(e.getPlateLength().setScale(2, RoundingMode.HALF_UP));
            e.setPlateWide(e.getPlateWide().setScale(2, RoundingMode.HALF_UP));
            e.setNestingPath(String.format(projectConfig.getUrlPre(), e.getNestingCode(), e.getNestingPath()));

            if (e.getSta() <= 2) {
                if (CompareUtil.compare(DateUtil.date().toString(), e.getPlanStartTime()) >= 0) {
                    e.setStatus(5);
                } else {
                    if (e.getTaskId() != null) {
                        //已就绪
                        e.setStatus(2);
                    } else {
                        if (StringUtils.isNotBlank(e.getRequisition())) {
                            if (e.getPlaStatus() >= 4) {
                                e.setStatus(1);
                            } else {
                                e.setStatus(8);
                            }
                        } else {
                            e.setStatus(8);
                        }
                    }
                }
            } else if (e.getSta() == 3) {
                if (CompareUtil.compare(e.getStartTime(), e.getPlanStartTime()) >= 0) {
                    e.setStatus(4);
                } else {
                    e.setStatus(3);
                }
                if (e.getWorkTime() != null && e.getStartTime() != null && e.getEndTime() == null) {
                    Long leftCutTime = LocalDateTime.parse(e.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).until(LocalDateTime.now(), ChronoUnit.SECONDS);
                    e.setLostTime(e.getWorkTime() - leftCutTime);
                }


            } else if (e.getSta() == 4) {
                if (CompareUtil.compare(e.getEndTime(), e.getPlanEndTime()) >= 0) {
                    e.setStatus(7);
                } else {
                    e.setStatus(6);
                }
                e.setLostTime(0L);
            } else {
                e.setStatus(6);
            }
            if (e.getPlaStatus().equals(3)) {
                e.setRequisition(e.getRequisition() + "(0/1)");
            } else if (e.getPlaStatus() >= 4) {
                e.setRequisition(e.getRequisition() + "(X)");
            }
        }
        //转换数据格式
        Page<WorkQueueTaskDetailResVo> pageList = new Page<>();
        BeanUtils.copyProperties(detailList, pageList);
        pageList.setRecords(detailList.getRecords().stream().map(e -> {
            WorkQueueTaskDetailResVo vo = new WorkQueueTaskDetailResVo();
            BeanUtils.copyProperties(e, vo);
            return vo;
        }).collect(Collectors.toList()));
        return BasePageResVo.of(pageList, WorkQueueTaskDetailResVo.class);
    }

    /**
     * @Description: 获取非钢板队列明细
     * @author: hejiahui
     * @since: 2024/9/19 16:4]
     */
    private BasePageResVo<WorkQueueTaskDetailResVo> getNoPlateWorkQueueDetail(WorkQueueTaskDetailReqVo reqVo) {
        Map<String, String> compareType = reqVo.getQueryType();
        //获取加工列表信息
        QueryWrapper<?> infoQuery = new QueryWrapper<>();
        //添加查询条件
        infoQuery.in("gr.id", reqVo.getGroupIds());
        infoQuery.eq("det.type", 2);
        infoQuery.ne("det.order_type", 2);
        infoQuery.in(ObjectUtils.isNotEmpty(reqVo.getOrderNos()), "ao.order_code", reqVo.getOrderNos());
        infoQuery.like(StringUtils.isNotBlank(reqVo.getOrderCode()), "ao.order_code", reqVo.getOrderCode());
        infoQuery.like(StringUtils.isNotBlank(reqVo.getConstructNo()), "ao.construct_no", reqVo.getConstructNo());
        infoQuery.like(StringUtils.isNotBlank(reqVo.getVersion()), "tsp.version_num", reqVo.getVersion());
        if (StringUtils.isNotBlank(reqVo.getPartName())) {
            infoQuery.like("det.mater_name", reqVo.getPartName());
        }
        if (StringUtils.isNotBlank(reqVo.getPlmid())) {
            infoQuery.like("det.mater_no", reqVo.getPlmid());
        }
        if (reqVo.getPlanStartDateTime() != null) {
            infoQuery.ge("det.plan_start_date_time", reqVo.getPlanStartDateTime());
        } else {
            infoQuery.ge("det.plan_start_date_time", LocalDateTime.now().minusDays(7));
        }
        if (reqVo.getPlanEndDateTime() != null) {
            infoQuery.le("det.plan_start_date_time", reqVo.getPlanEndDateTime().plusDays(1));
        } else {
            infoQuery.le("det.plan_start_date_time", LocalDateTime.now().plusDays(7));
        }
        if (reqVo.getStatus() != null) {
            if (reqVo.getStatus() < 4) {
                infoQuery.lt("det.status", 4);
            } else {
                infoQuery.eq("det.status", reqVo.getStatus());
            }
        }
        if (StringUtils.isNotBlank(reqVo.getPackageNo())) {
            int packagerNo = PkgUtils.rollBack(reqVo.getPackageNo());
            infoQuery.eq("ao.seq", packagerNo);
        }
        if (ObjectUtils.isNotEmpty(reqVo.getThick())) {
            WrapperUtil.fixWrapper(infoQuery, "ao.construct_no", compareType.get("thick"), reqVo.getThick());
        }
        infoQuery.like(StringUtils.isNotBlank(reqVo.getSizeMaterial()), "tsp.texture", reqVo.getSizeMaterial());
        //添加排序条件
        String orderStr = "det.plan_start_date_time";
        if (StringUtils.isNotBlank(reqVo.getSort())) {
            if ("planStartTime".equals(reqVo.getSort())) {
                orderStr = "det.plan_start_date_time";
            } else if ("planEndTime".equals(reqVo.getSort())) {
                orderStr = "det.plan_end_date_time";
            } else if ("startTime".equals(reqVo.getSort())) {
                orderStr = "det.actual_start_date_time";
            } else if ("endTime".equals(reqVo.getSort())) {
                orderStr = "det.actual_end_date_time";
            }
        }

        Page<NoPlateWorkQueueTaskDetail> detailList = null;
        if (reqVo.getWorkArea().equals("smartWeldingArea") || reqVo.getWorkArea().equals("processDeliveryArea")) {
            orderStr = " min(det.plan_start_date_time) ";
            if (StringUtils.isNotBlank(reqVo.getOrder())) {
                if ("desc".equals(reqVo.getOrder())) {
                    infoQuery.orderByDesc(orderStr);
                } else {
                    infoQuery.orderByAsc(orderStr);
                }
            } else {
                infoQuery.orderByAsc(orderStr);
            }
            infoQuery.groupBy(" det.order_id, det.aps_work_order_id, det.phase_code, det.mater_no, det.mater_name,op.work_time,aword.mater_weight , ao.construct_no, ao.order_code ");
            detailList = baseMapper.getSmartWeldingAreaDetail(reqVo.toPage(), infoQuery);
        } else {
            if (StringUtils.isNotBlank(reqVo.getOrder())) {
                if ("desc".equals(reqVo.getOrder())) {
                    infoQuery.orderByDesc(orderStr);
                } else {
                    infoQuery.orderByAsc(orderStr);
                }
            } else {
                infoQuery.orderByAsc(orderStr);
            }
            detailList = baseMapper.getNoPlateWorkQueueDetail(reqVo.toPage(), infoQuery);


            if (!reqVo.getWorkArea().equals("plateMatingArea") &&ObjectUtils.isNotEmpty(detailList.getRecords())) {
                List<Integer> awdIds = detailList.getRecords().stream().map(NoPlateWorkQueueTaskDetail::getAwId).collect(Collectors.toList());
                List<WorkqueueNetDetail> nestInfos = baseMapper.getNestInfoCount(awdIds);
                Map<Integer, WorkqueueNetDetail> netInfo = nestInfos.stream().collect(Collectors.toMap(WorkqueueNetDetail::getApsWorkOrderId, Function.identity(), (v1, v2) -> v1));
                detailList.getRecords().forEach(
                        e -> {
                            WorkqueueNetDetail stringObjectMap = netInfo.get(e.getAwId());
                            if (stringObjectMap != null && stringObjectMap.getTlCount() != null) {
                                e.setNestCnt(stringObjectMap.getTlCount());
                            } else {
                                e.setNestCnt(0);
                            }
//                            e.setNestCnt(stringObjectMap != null ? stringObjectMap.getTlCount() != null ? stringObjectMap.getTlCount() : 0 : 0);
                        }
                );

            }else if(reqVo.getWorkArea().equals("plateMatingArea") &&ObjectUtils.isNotEmpty(detailList.getRecords())){
                /*
                List<Integer> awdIds = detailList.getRecords().stream().map(NoPlateWorkQueueTaskDetail::getQgId).collect(Collectors.toList());
                List<WorkqueueNetDetail> nestInfos = baseMapper.getNestInfoCount(awdIds);
                Map<Integer, WorkqueueNetDetail> netInfo = nestInfos.stream().collect(Collectors.toMap(WorkqueueNetDetail::getApsWorkOrderId, Function.identity(), (v1, v2) -> v1));
                detailList.getRecords().forEach(
                        e -> {
                            WorkqueueNetDetail stringObjectMap = netInfo.get(e.getAwId());
                            if (stringObjectMap != null && stringObjectMap.getTlCount() != null) {
                                e.setNestCnt(stringObjectMap.getTlCount());
                            } else {
                                e.setNestCnt(0);
                            }
//                            e.setNestCnt(stringObjectMap != null ? stringObjectMap.getTlCount() != null ? stringObjectMap.getTlCount() : 0 : 0);
                        }
                );

                 */

                List<String> collect1 = detailList.getRecords().stream().map(e -> String.valueOf(e.getQgId())).distinct().collect(Collectors.toList());

                List<SinoCamReceiveNestPart> nestPart = sinoCamReceiveNestPartMapper.lambdaQuery().in(SinoCamReceiveNestPart::getNestPlanId, collect1).list();
                Map<String, Integer> collect = nestPart.stream().collect(Collectors.groupingBy(SinoCamReceiveNestPart::getNestPlanId, Collectors.summingInt(e -> e.getQuantity().intValue())));

                for (NoPlateWorkQueueTaskDetail record : detailList.getRecords()) {
                    if(record.getQgId() == null){
                        record.setNestCnt(0);
                    } else {
                        record.setNestCnt(collect.getOrDefault(record.getQgId().toString(), 0));
                    }
                }
            }
        }
        List<NoPlateWorkQueueTaskDetail> records = detailList.getRecords();
        if (ObjectUtils.isEmpty(records)) {
            return BasePageResVo.empty();
        }
        //获取零件图纸   状态:1等待已领料、2就绪、3生产中、4生产已晚、5已晚、6完工、7完工已晚、8等待未领料
        records.forEach(e -> {
            e.setPartPath(String.format(projectConfig.getUrlPre(), e.getPlmid(), e.getPartPath()));
            if (e.getPackageNo() != null) {
                e.setPackageNo(PkgUtils.gen(Integer.parseInt(e.getPackageNo())));
            }

            if (e.getSta() == 3) {
                Long leftCutTime = LocalDateTime.parse(e.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).until(LocalDateTime.now(), ChronoUnit.SECONDS);
                e.setLostTime(e.getWorkTime() - leftCutTime);
            }
            //未开工状态
            if (e.getSta() <= 2) {
                if (CompareUtil.compare(DateUtil.date().toString(), e.getPlanStartTime()) >= 0) {
                    e.setStatus(5);
                } else {
                    if (ObjectUtils.isNotEmpty(e.getTkId())) {
                        //已就绪
                        e.setStatus(2);
                    } else {
                        e.setStatus(1);
                    }
                }
            }
            //已开工状态
            else if (e.getSta() == 3) {
                if (CompareUtil.compare(e.getStartTime(), e.getPlanStartTime()) >= 0) {
                    e.setStatus(4);
                } else {
                    e.setStatus(3);
                }
            }
            //已完工状态1
            else if (e.getSta() == 4) {
                if (CompareUtil.compare(e.getEndTime(), e.getPlanEndTime()) >= 0) {
                    e.setStatus(7);
                } else {
                    e.setStatus(6);
                }
            } else {
                e.setStatus(6);
            }
        });
        //转换数据格式
        Page<WorkQueueTaskDetailResVo> pageList = new Page<>();
        BeanUtils.copyProperties(detailList, pageList);
        pageList.setRecords(detailList.getRecords().stream().map(e -> {
            WorkQueueTaskDetailResVo vo = new WorkQueueTaskDetailResVo();
            BeanUtils.copyProperties(e, vo);
            vo.setSizeMaterial(e.getSize());
            return vo;
        }).collect(Collectors.toList()));
        return BasePageResVo.of(pageList, WorkQueueTaskDetailResVo.class);
    }


    public Result<List<WorkPhaseVo>> getWorkPhase(DictDataFindReqVo reqVo) {

        if (reqVo.getDictTypeCode().equals("nest")) {
            WorkPhaseVo vo = new WorkPhaseVo();
            vo.setPhaseCode("NEST");
            return Result.success(Arrays.asList(vo));
        }

        List<String> workGroupList = null;
        if (StringUtils.isNotBlank(reqVo.getDictTypeCode())) {
            QueryWrapper<DictData> query = Wrappers.query();
            query.eq("dt.dict_code", reqVo.getDictTypeCode());
            query.eq("dd.deleted", 0);
            List<DictData> byDictTypeCode = dictDataMapper.findByDictTypeCode(query);
            workGroupList = byDictTypeCode
                    .stream()
                    .map(DictData::getDictLabel)
                    .collect(Collectors.toList());
        }

        LambdaQueryWrapper<PhaseGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(workGroupList != null, PhaseGroup::getGroupCode, workGroupList);
        wrapper.eq(PhaseGroup::getDeleted, 0);
        List<PhaseGroup> phaseGroups = phaseMapper.selectList(wrapper);
        Set<String> set = phaseGroups.stream().map(PhaseGroup::getPhaseCode).collect(Collectors.toSet());
        List<WorkPhaseVo> phaseList = set.stream()
                .map(e -> {
                    WorkPhaseVo vo = new WorkPhaseVo();
                    vo.setPhaseCode(e);
                    return vo;
                })
                .collect(Collectors.toList());
        return Result.success(phaseList);
    }
}
